package com.example.gymnasiumsystem.servlet;

import com.example.gymnasiumsystem.dao.UserInfoDAO;
import com.example.gymnasiumsystem.enity.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserInfoDAO userInfoDAO = new UserInfoDAO();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/admin/login.jsp").forward(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // 设置请求字符编码为UTF-8
        response.setContentType("text/html;charset=UTF-8");  // 设置响应字符编码为UTF-8
        String UserNumber = request.getParameter("username");
        String password = request.getParameter("password");
        // 验证图形验证码
        HttpSession session = request.getSession();
        // 验证学号和密码
        UserInfo userInfo = userInfoDAO.getUserByUsername(UserNumber);
        if (userInfo != null && userInfo.getUsername().equals(UserNumber) && password.equals(userInfo.getPassword())) { // 假设密码为12345
            session.setAttribute("user", userInfo);
            if(userInfo.getIsAdmin()==0){
                response.sendRedirect("gymList.jsp");
                return;
            }
            response.sendRedirect("admin/gymList.jsp"); // 登录成功后跳转到活动展示列表
        } else {
           response.sendRedirect("admin/error.jsp");
        }
    }
}
